<template>
  <div class="todo-footer" v-if="total > 0">
    <input type="checkbox" v-model="isAll" class="foot-checkbox" />
    <span>已完成 {{ doneTotal }} / 全部 {{ total }}</span>
    <button class="btn-Completed" @click="clearCompleted">清除已完成任务</button>
    <button class="btn-clearAll" @click="clearAll">清除所有任务</button>
  </div>
  <div v-else class="noneItem">
    暂无代办事项
  </div>
</template>

<script setup>
import { ref, computed,watch } from 'vue';

// 定义接收的 props
const props = defineProps({
  todos: {
    type: Array,
    required: true,
  },
  checkAllTodo: {
    type: Function,
    required: true,
  },
  clearAllTodo: {
    type: Function,
    required: true,
  },
  clearCompletedTodo: {
    type: Function,
    required: true,
  },
})

// 使用 ref 创建响应式引用
const isAll = ref(false)

// 使用 computed 定义计算属性
const total = computed(() => props.todos.length)
const doneTotal = computed(() => {
  return props.todos.reduce((pre, todo) => pre + (todo.check ? 1 : 0), 0)
})
// 确保加载时的checkbox状态与已完成任务数一致
const isAllChecked = computed(() => doneTotal.value === total.value && total.value > 0)
isAll.value = isAllChecked.value
// 监听 isAll 的变化，并调用 checkAllTodo 方法
watch(isAll, (newValue) => {
  props.checkAllTodo(newValue)
})
// 监听 todos 的变化，以更新全选状态
watch(doneTotal, (newValue) => {
  // 当所有任务都完成时，设置 isAll 为 true
  if (newValue === total.value && total.value > 0) {
    isAll.value = true
  }
})

// 从props中获取方法
const clearAll = () => {
  props.clearAllTodo()
}

const clearCompleted = () => {
  props.clearCompletedTodo()
}
</script>

<style>
.noneItem{
    text-align: center;
    font-size: 2em;
    font-weight: 700;
}
.todo-footer{
    display: flex;
    position:relative;
    align-items: center;
    padding: 10px;
    border-top: 1px solid #ccc;
    background-color: lightblue;
}
.foot-checkbox{
    margin-right: 10px;
    cursor: pointer;
    width: 20px;
    height: 15px;
    border-radius: 50%;
    margin-left: 10px;
    visibility: hidden;
}
.btn-Completed,.btn-clearAll{
    position: absolute;
    right: 20px;
    margin-left: 10px;
    padding: 5px 10px;
    border-radius: 5px;
    background-color: #41b883;
    color: #fff;
    border: none;
    cursor: pointer;
}
.btn-clearAll{
    right: 160px;
}
.foot-checkbox::before {
  content: '';
  position: absolute;
  border-color: blue;
  border-style: solid;
  border-width: 0 3px 3px 0;
  top: 20px;
  left: 22px;

  transform: rotate(-135deg);
  height: 10px;
  width: 10px;
  visibility: visible;
}
</style>